﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using UtfUnknown;
using System.IO;
using System.Text.RegularExpressions;

namespace TextNovelReader.Model;

/// <summary>
/// 主要目的：从文件读取小说的内容，解码，并生成所有的章对象。
/// </summary>
public partial class ChapterManager(string filePath)
{
    private readonly string _filePath = filePath;

    private async Task<Encoding> GetFileEncodingAsync()
    {
        DetectionResult result = await CharsetDetector.DetectFromFileAsync(_filePath);
        return result.Detected.Encoding; 
    }

    private static bool IsTitleLine(ref string line)
    {
        var regex = TitleRegex();
        var input = line.Length <= 12 ? line : line[..12]; 
        var matchResult =  regex.Match(input);
        return matchResult.Success; 
    }

    public async Task<IEnumerable<Chapter>> GetChaptersAsync()
    {
        Encoding encoding = await GetFileEncodingAsync();

        using var stream = new FileStream(_filePath, FileMode.Open);
        using var reader = new StreamReader(stream, encoding);

        List<Chapter> result = []; 

        StringBuilder textBuilder = new();
        string title = string.Empty; 

        string line = string.Empty; 
        while (!reader.EndOfStream)
        {
            line = reader.ReadLine() ?? string.Empty; 
            if(IsTitleLine(ref line))
            {
                title = line; 
                break; 
            }
        }

        if (string.IsNullOrEmpty(title))
        {
            result.Add(new Chapter("读取目录失败", "", result.Count)); 
            return result; 
        }

        while (!reader.EndOfStream)
        {
            line = reader.ReadLine() ?? string.Empty; 
            if(!IsTitleLine(ref line))
            {
                if (string.IsNullOrEmpty(line))
                    continue;
                textBuilder.AppendLine(line); 
            }
            else
            {
                result.Add(new Chapter(title, textBuilder.ToString(), result.Count));

                title = line;
                textBuilder = textBuilder.Clear(); 
            }
        }

        result.Add(new Chapter(title, textBuilder.ToString(), result.Count));
        return result;
    }

    [GeneratedRegex(@"第\s?[\d零一二三四五六七八九十百千万]+\s?章")]
    private static partial Regex TitleRegex();
}
